function UpdateMessageCount()
{
	XHR.SendRequest("/", (function(xhr)
	{
		var windid = xhr.responseText.match(/var\s*windid\s*=\s*'(.*?)';/);
		var result = xhr.responseText.match(
			/<span id="msgnum_show">(\d*)<\/span>/);
		if(result)
			chrome.browserAction.setBadgeText({text: result[1]});
		else if(windid && windid[1])
			chrome.browserAction.setBadgeText({text: ""});
		else
			chrome.browserAction.setBadgeText({text: "?"});
	}), (function()
	{
		chrome.browserAction.setBadgeText({text: "!"});
	}) );
}

var MessageEntryRegEx_String = '<td><a href="u\\.php\\?action=show&uid=(\\d+)">(.*?)</a></td>\\s*<td><a href="message\\.php\\?action=(readn?)&mid=(\\d+)">(.*?)</a></td>\\s*<td>(.*?)</td>';
var MessageEntryRegEx = new RegExp();
var MessageEntryRegExG = new RegExp();
MessageEntryRegEx.compile(MessageEntryRegEx_String, "i");
MessageEntryRegExG.compile(MessageEntryRegEx_String, "ig");

function ReadNewMessages(callback)
{
	XHR.SendRequest("/message.php?type=newmsg", (function(xhr)
	{
		var results = [];
		var messages = xhr.responseText.match(
			/<tr><td colspan="5"><b>未读(个人|系统)短消息<\/b><\/td><\/tr>[\s\S]*?<\/table>/);
		if(!messages)
		{
			callback(results);
			return;
		}
		var entries = messages[0].match(MessageEntryRegExG);
		if(!entries)
		{
			callback(results);
			return;
		}
		for(var i = 0; i < entries.length; ++i)
		{
			var matches = entries[i].match(MessageEntryRegEx);
			if(matches)
				results[results.length] = 
				{
					fromUid: matches[1], 
					fromUser: matches[2], 
					actionId: matches[3], 
					id: matches[4], 
					title: matches[5], 
					time: matches[6], 
				};
		}
		chrome.browserAction.setBadgeText({text: results.length.toString()});
		callback(results);
	}), (function(xhr)
	{
		callback();
	}));
}

(chrome.extension.onMessage || chrome.extension.onRequest).addListener(
function(message, sender, sendResponse)
{
	if(message.name && message.name == "updateMessageCount" && 
		message.value != undefined)
	{
		if(/^(\d*|\?)$/.test(message.value))
			chrome.browserAction.setBadgeText({text: message.value});
		console.log("updateMessageCount: source=" + message.source);
	}
});

interval_UpdateMessageCount = window.setInterval(UpdateMessageCount, 60000);

